import React, { useRef, useEffect, useState, useCallback } from 'react';
import MessageItem from './MessageItem';
import StreamDataRenderer from './StreamDataRenderer';

const MessageList = ({ messages, isLoading, currentStreamData, onItemHover, onItemLeave, onLoadMoreHistory, hasMoreHistory }) => {
    const messagesEndRef = useRef(null);
    const messagesContainerRef = useRef(null);
    const [isLoadingMore, setIsLoadingMore] = useState(false);
    const [shouldScrollToBottom, setShouldScrollToBottom] = useState(true);
    const [isFirstLoad, setIsFirstLoad] = useState(true);
    const [previousScrollHeight, setPreviousScrollHeight] = useState(0);

    const scrollToBottom = useCallback((immediate = false) => {
        if (shouldScrollToBottom && messagesContainerRef.current) {
            const container = messagesContainerRef.current;
            container.scrollTop = container.scrollHeight;
            
            // 如果需要平滑滚动
            if (!immediate && messagesEndRef.current) {
                messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
            }
        }
    }, [shouldScrollToBottom]);

    // 处理首次加载和会话切换时的滚动
    useEffect(() => {
        // 首次加载或会话切换后，确保滚动到底部
        if (messages.length > 0 && isFirstLoad) {
            // 使用requestAnimationFrame确保DOM已渲染
            requestAnimationFrame(() => {
                scrollToBottom(true); // 立即滚动到底部
                setIsFirstLoad(false);
            });
        }
    }, [messages.length, isFirstLoad, scrollToBottom]);

    // 处理加载更多历史记录时的滚动位置保持
    useEffect(() => {
        if (messagesContainerRef.current && !isFirstLoad && previousScrollHeight > 0) {
            const container = messagesContainerRef.current;
            const newScrollHeight = container.scrollHeight;
            const scrollDiff = newScrollHeight - previousScrollHeight;
            
            // 保持在相同的视觉位置
            if (scrollDiff > 0) {
                container.scrollTop += scrollDiff;
            }
        }
    }, [messages.length, previousScrollHeight, isFirstLoad]);

    // 处理流式数据更新的滚动
    useEffect(() => {
        if (currentStreamData.length > 0 && shouldScrollToBottom) {
            scrollToBottom();
        }
    }, [currentStreamData, scrollToBottom, shouldScrollToBottom]);

    // 处理新消息的滚动（用户发送消息或接收回复）
    useEffect(() => {
        // 当有新消息且应该滚动到底部时
        if (messages.length > 0 && !isFirstLoad && shouldScrollToBottom) {
            scrollToBottom();
        }
    }, [messages.length, isFirstLoad, shouldScrollToBottom, scrollToBottom]);

    // 当消息列表重置时（切换会话），重置滚动状态
    useEffect(() => {
        if (messages.length === 0) {
            setShouldScrollToBottom(true);
            setIsFirstLoad(true);
            setPreviousScrollHeight(0);
        }
    }, [messages.length]);

    // 处理滚动事件，检测是否需要加载更多历史记录
    const handleScroll = useCallback(async (e) => {
        const container = e.target;
        const scrollTop = container.scrollTop;
        const threshold = 50; // 距离顶部50px时开始加载
        
        // 用户手动滚动时，暂停自动滚动到底部
        const containerHeight = container.scrollHeight - container.clientHeight;
        const isNearBottom = containerHeight - scrollTop < 100;
        
        if (!isNearBottom) {
            setShouldScrollToBottom(false);
        } else {
            setShouldScrollToBottom(true);
        }
        
        if (scrollTop <= threshold && !isLoadingMore && messages.length > 0 && hasMoreHistory) {
            setIsLoadingMore(true);
            
            // 记录当前的滚动高度，用于加载后保持位置
            setPreviousScrollHeight(container.scrollHeight);
            
            try {
                if (onLoadMoreHistory) {
                    await onLoadMoreHistory();
                }
            } catch (error) {
                console.error('加载更多历史记录失败:', error);
            } finally {
                setIsLoadingMore(false);
            }
        }
    }, [isLoadingMore, messages.length, onLoadMoreHistory, hasMoreHistory]);

    return (
        <div 
            className="messages" 
            ref={messagesContainerRef}
            onScroll={handleScroll}
        >
            {/* 加载更多历史记录的提示 */}
            {isLoadingMore && hasMoreHistory && (
                <div className="loading-more-history">
                    <div className="loading-spinner">加载更多历史记录...</div>
                </div>
            )}
            
            {/* 没有更多历史记录的提示 */}
            {!hasMoreHistory && messages.length > 0 && (
                <div className="no-more-history">
                    <div className="no-more-text">已显示全部历史记录</div>
                </div>
            )}
            

            {messages.map((message, index) => {
                const key = message.messageId || message.id || message.createTime || `${message.type}-${index}`;
                return (
                    <MessageItem 
                        key={key}
                        message={message}
                        onItemHover={onItemHover}
                        onItemLeave={onItemLeave}
                    />
                );
            })}

            {isLoading && (
                <div className="message assistant">
                    <div className="bot-avatar">
                        <img src="/assets/logo/u5.png" alt="AI Assistant" />
                    </div>
                    <div className="bot-message">
                        {currentStreamData.length > 0 ? (
                            <StreamDataRenderer
                                data={currentStreamData}
                                onItemHover={onItemHover}
                                onItemLeave={onItemLeave}
                            />
                        ) : (
                            <div className="loading">正在思考...</div>
                        )}
                    </div>
                </div>
            )}

            <div ref={messagesEndRef} />
        </div>
    );
};

export default MessageList;